<!DOCTYPE html>
<!--
Copyright (c) 2013 The Chromium Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
-->

<link rel="import" href="/tracing/base/xhr.html">
<link rel="import" href="/tracing/core/test_utils.html">
<link rel="import" href="/tracing/extras/importer/trace_event_importer.html">
<link rel="import" href="/tracing/model/model.html">

<script>
'use strict';

tr.b.unittest.testSuite(function() {
  const eventStrings = {};

  // @const
  const N_ITERATIONS = 200;

  // @const
  const TEST_NAMES = [
    'simple_trace',
    'flow',
  ];
  // @const
  const TEST_FILES_PATHS = [
    '/test_data/simple_trace.json',
    '/test_data/flow.json',
  ];

  function stringToStream(str) {
    const buffer = new ArrayBuffer(str.length);
    const bufferView = new Uint8Array(buffer);
    for (let i = 0; i < bufferView.length; i++) {
      bufferView[i] = str.charCodeAt(i);
    }
    const stream = new tr.b.InMemoryTraceStream(bufferView, false);
    return stream;
  }

  function getEvents(url, asStream) {
    if (url in eventStrings && asStream in eventStrings[url]) {
      return eventStrings[url][asStream];
    }
    if (!(url in eventStrings)) {
      eventStrings[url] = {};
    }
    // TODO(ehmaldonado): See catapult:#3845.
    // tr.b.getSync does not return a trace stream in browser mode, so we
    // convert to stream manually.
    eventStrings[url][asStream] = tr.b.getSync(url);
    if (asStream) {
      eventStrings[url][asStream] = stringToStream(eventStrings[url][asStream]);
    }
    return eventStrings[url][asStream];
  }

  function timedPerfTestWithEvents(name, testFn, initialOptions, asStream) {
    if (initialOptions.setUp) {
      throw new Error(
          'Per-test setUp not supported. Trivial to fix if needed.');
    }

    const options = {};
    for (const k in initialOptions) {
      options[k] = initialOptions[k];
    }
    options.setUp = function() {
      TEST_FILES_PATHS.forEach(
          function warmup(url) {
            getEvents(url, asStream);
          });
    };
    timedPerfTest(name, testFn, options);
  }

  for (let i = 0; i < TEST_NAMES.length; ++i) {
    const testName = TEST_NAMES[i];
    const testFilePath = TEST_FILES_PATHS[i];

    // Import trace as a string.
    timedPerfTestWithEvents(testName + '_string', function() {
      const events = getEvents(testFilePath, false);
      const m = tr.c.TestUtils.newModelWithEvents([events], {
        shiftWorldToZero: false,
        pruneContainers: false
      });
    }, {iterations: N_ITERATIONS}, false);

    // Import trace as a stream.
    timedPerfTestWithEvents(testName + '_stream', function() {
      const events = getEvents(testFilePath, true);
      const m = tr.c.TestUtils.newModelWithEvents([events], {
        shiftWorldToZero: false,
        pruneContainers: false
      });
    }, {iterations: N_ITERATIONS}, true);
  }
});
</script>

